package com.sc.nft.admin.controller;

import com.sc.nft.admin.request.EcologyHatchMapRatioRequest;
import com.sc.nft.annotation.UserLogin;
import com.sc.nft.entity.vo.EcologyHatchMetaMapVO;
import com.sc.nft.enums.RedisKeyEnum;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.EcologyHatchRatioService;
import com.sc.nft.sup.PageResult;
import com.sc.nft.sup.Result;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

/**
 * 熔炼权益配置服务控制器
 *
 * @author jinpinhai
 * @since 2024-09-06 16:29:30
 * @description Generator
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/admin/ecologyHatchRatio")
public class EcologyHatchRatioController {

    private final EcologyHatchRatioService ecologyHatchRatioService;
    private final Redisson redisson;


    @ApiOperation(value = "获取版图权益比例", notes = "获取熔炼剩余份数", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/findMetaMapRatio", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public Result<EcologyHatchMetaMapVO> findMetaMapRatio() {
        return PageResult.success(ecologyHatchRatioService.findMetaMapRatio());
    }

    @ApiOperation(value = "保存版图权益比例", notes = "获取熔炼剩余份数", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/saveMetaMapRatio", produces = MediaType.APPLICATION_JSON_VALUE)
    @UserLogin
    public Result<EcologyHatchMetaMapVO> saveMetaMapRatio(@Valid @RequestBody EcologyHatchMapRatioRequest request) {
        request.checkRatio();
        RLock lock = redisson.getLock(RedisKeyEnum.SETTLE_MATE_MAP_RATIO.getKey());
        try {
            boolean res = lock.tryLock();
            if (!res) {
                throw new GlobalRunTimeException("太火爆了,请稍后再试");
            }
            ecologyHatchRatioService.saveMetaMapRatio(request.getMetaMapProvinceRatio(), request.getMetaMapCityRatio(), request.getMetaMapRegionRatio());
        } catch (GlobalRunTimeException e) {
            log.error("保存版图权益比例异常", e);
            throw e;
        } finally {
            if (lock.isLocked()) {
                lock.unlock();
            }
        }
        return Result.success();
    }

}